<template>
  <div class="wrap">
    <div class="page-head">
      <a-breadcrumb>
        <a-breadcrumb-item>{{ $t('spectRecord.spectRecord.60zelpzse040') }}</a-breadcrumb-item>
        <a-breadcrumb-item>{{ $t('spectRecord.spectRecord.60zelpzse042') }}</a-breadcrumb-item>
      </a-breadcrumb>
    </div>
    <c-table-search :loading="form.loading" v-model:model="form.data" @refresh="getData">
      <a-col :span="8">
        <a-form-item field="objectId" :label="$t('spectRecord.spectRecord.60zelpzsjy15')">
          <a-input v-model="form.data.objectId" :placeholder="$t('spectRecord.spectRecord.60zelpzsjy16')" />
        </a-form-item>
      </a-col>
      <a-col :span="8">
        <a-form-item field="value" :label="$t('spectRecord.spectRecord.60zelpzsfbo0')">
          <a-range-picker :model-value="[form.data.startTime, form.data.endTime]"
            style="width: 360px; margin: 0 24px 24px 0;" show-time format="YYYY-MM-DD HH:mm" @change="form.data.startTime = Number($event?.[0]);
            form.data.endTime = Number($event?.[1])" value-format="x" />
        </a-form-item>
      </a-col>
      <template v-slot:refresh>
        <a-button type="outline" @click="refresh">
          <template #icon>
            <icon-loop />
          </template>
        </a-button>
      </template>
      <template v-slot:export>
        <a-button type="primary" :loading="form.downloading" v-permission="['fiveGASpectRecord:export']"
          @click="exportExcel">
          <template #icon>
            <icon-share-external />
          </template>
          {{ $t('spectRecord.spectRecord.60zelpzsfpc0') }}
        </a-button>
      </template>
      <!-- <template v-slot:playback>
        <a-button type="primary">
            <template #icon>
              <icon-play-circle />
            </template>
            {{$t('spectRecord.spectRecord.60zelpzsfzs0')}}
          </a-button>
      </template> -->
    </c-table-search>
    <div class="table-scroll">
      <c-table :list="sortList" :loading="form.loading" :count="form.count" v-model:data="form.data"
      @sorterChange="handleSort" @refresh="getData">
        <a-table-column :title="$t('spectRecord.spectRecord.60zelpzsg7o0')" ellipsis tooltip :width="60">
          <template #cell="{ rowIndex }">
            {{ rowIndex + 1 }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('spectRecord.spectRecord.60zelpzsfbo1')" ellipsis tooltip :width="320">
          <template #cell="{ record }">
            {{ record.objectId ? record.objectId : '-' }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('spectRecord.spectRecord.60zelpzsji00')" ellipsis tooltip :sortable="{
          sortDirections: ['ascend', 'descend'],
          sorter: true
        }" data-index="startTime" :width="180">
          <template #cell="{ record }">
            {{ record.startTime ? dayjs.unix(record.startTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('spectRecord.spectRecord.60zelpzsjtk0')" ellipsis tooltip :sortable="{
          sortDirections: ['ascend', 'descend'],
          sorter: true
        }" data-index="endTime" :width="180">
          <template #cell="{ record }">
            {{ record.endTime ? dayjs.unix(record.endTime).format('YYYY-MM-DD HH:mm:ss') : '-' }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('spectRecord.spectRecord.60zelpzsjtk1')" ellipsis tooltip :width="120">
          <template #cell="{ record }">
            {{ Math.abs(record.speed) ? Math.abs(record.speed) : '-' }}
          </template>
        </a-table-column>
        <!-- <a-table-column :title="$t('spectRecord.spectRecord.60zelpzskcg0')" ellipsis tooltip :width="120">
          <template #cell="{ record }">
            {{ Math.abs(record.height) ? Math.abs(record.height) : '-' }}
          </template>
        </a-table-column> -->
        <a-table-column :title="$t('spectRecord.spectRecord.60zelpzsjy13')" ellipsis tooltip :width="120">
          <template #cell="{ record }">
            {{ Math.abs(record.altitude) ? Math.abs(record.altitude) : '-' }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('spectRecord.spectRecord.60zelpzskfw0')" ellipsis tooltip :sortable="{
          sortDirections: ['ascend', 'descend'],
          sorter: true
        }" data-index="second"  :width="150">
          <template #cell="{ record }">
            {{ record.second ? record.second : '-' }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('spectRecord.spectRecord.60zelpzsjyg0')" ellipsis tooltip :width="200">
          <template #cell="{ record }">
            {{ record.longitude }},{{ record.latitude }}
          </template>
        </a-table-column>
        <a-table-column :title="$t('spectRecord.spectRecord.60zelpzsj1w0')" ellipsis tooltip :width="150">
          <template #cell="{ record }">
            <a-tag color="#f53f3f" v-if="record?.status == 7">{{ $t('spectRecord.spectRecord.60zelpzsj7o0') }}</a-tag>
            <a-tag color="#00b42a" v-else>{{ $t('spectRecord.spectRecord.60zelpzsjc80') }}</a-tag>
          </template>
        </a-table-column>
        <a-table-column :title="$t('spectRecord.spectRecord.60zelpzskjg0')" fixed='right' :width="150">
          <template #cell="{ record }">
            <a-space>
              <a-button type="text" v-permission="['fiveGASpectRecord:playback']" @click="playback(record)">{{
                $t('spectRecord.spectRecord.60zelpzsfzs0')
              }}</a-button>
              <a-button type="text" v-permission="['fiveGASpectRecord:detail']" @click="detail(record)">{{
                $t('spectRecord.spectRecord.60zelpzsomc0') }}</a-button>
            </a-space>
          </template>
        </a-table-column>
      </c-table>
      <cNone v-if="!form.list?.length"></cNone>
      <Detail @refresh="getData" v-model:show="form.detail.show" v-model:data="form.detail.data"></Detail>
      <Playback @refresh="getData" v-model:show="form.playback.show" v-model:data="form.playback.data"></Playback>
    </div>
  </div>
</template>

<script lang='ts' setup>
// @ts-ignore
import { saveAs } from 'file-saver';
import ExcelJS from 'exceljs';
import { apiFiveGARecordList } from '@/api/record'
import dayjs from 'dayjs'
import Playback from './components/playback.vue';
// 根据经纬度解析地址
// import { initAMapApiLoader, lazyAMapApiLoaderInstance } from '@vuemap/vue-amap';
// 初始化地图
// if(!(window as any).AMap.Geocoder){
//   initAMapApiLoader({
//     key: 'e43a0ad8b98bf1a534d7b781c88fcf69',
//     securityJsCode: '329e292c553ad7264998323cf9c13c9d',
//     plugins: ['AMap.Geocoder']
//   });
// }
// initAMapApiLoader({
//   key: 'e43a0ad8b98bf1a534d7b781c88fcf69',
//   securityJsCode: '329e292c553ad7264998323cf9c13c9d',
//   plugins: ['AMap.Geocoder']
// });
const Detail = defineAsyncComponent(() => import('./components/detail.vue'))
const local = useLocal()
const route = useRoute()
const emit = defineEmits(['refresh'])
const refresh = () => {
  emit('refresh')
}
const form = reactive({
  detail: {
    show: false,
    data: {},
  },
  playback: {
    show: false,
    data: {},
  },
  // auths:[],
  // allAuths:[],
  data: {
    startTime: dayjs().subtract(7, 'day').format('YYYY-MM-DD HH:mm:ss'),
    endTime: dayjs().format('YYYY-MM-DD HH:mm:ss'),
    // keywords: '',
    objectId:'',
    page: 1,
    pageSize: 10,
    uid: local.usermsg.id == 3 ? 0 : local.usermsg.id
  } as any,
  downloading: false,
  loading: false,
  list: [] as any,
  count: 0
})
const dataIndex = ref();
const direction = ref()
// 无人机侦测记录列表
const getData = async () => {
  form.loading = true
  const { code, data } = await apiFiveGARecordList({
    ...form.data,
    startTime: Number(dayjs(form.data.startTime).format('X')),
    endTime: Number(dayjs(form.data.endTime).format('X')),
    // keywords: form.data.keywords,
  })
  form.loading = false
  if (code != 200) return;
  form.list = data.list
  form.count = data.total
}
// 排序
const sortList = computed(() => {
  if(direction.value == '') return form.list
  return ([...form.list] as any).sort((a: any, b: any) => {
    if(direction.value == 'ascend') return a[dataIndex.value] - b[dataIndex.value]
    return b[dataIndex.value] - a[dataIndex.value]
  })
})
const handleSort = (field: any, sort: any) => {
  dataIndex.value = field
  direction.value = sort
}
// 选择时间
// const onOk = (dateString: any, date: any) => {
//   console.log('onOk: ', dateString, date)
// }
// const uavTypes: any = {
//   '1': {
//     name: t('components.aircraftType.60zeao6x8h40'),
//     color: '#5470c6'
//   },
//   '2': {
//     name: t('components.aircraftType.60zeao6x9wk0'),
//     color: '#9a60b4'
//   },
//   '3': {
//     name: t('components.aircraftType.60zeao6xa340'),
//     color: '#fc8452'
//   },
//   '4': {
//     name: t('components.aircraftType.60zeao6xa840'),
//     color: '#3ba272'
//   },
//   '5': {
//     name: t('components.aircraftType.60zeao6xads0'),
//     color: '#73c0de'
//   },
//   '6': {
//     name: t('components.aircraftType.60zeao6xaik0'),
//     color: '#ee6666'
//   },
//   '7': {
//     name: t('components.aircraftType.60zeao6xano0'),
//     color: '#fac858'
//   },
//   '8': {
//     name: t('components.aircraftType.60zeao6xas40'),
//     color: '#91cc75'
//   },
//   '9': {
//     name: t('components.aircraftType.60zeao6xaw80'),
//     color: '#ea7ccc'
//   },
// }
//导出excel表
const exportExcel = async () => {
  form.downloading = true
  const workbook = new ExcelJS.Workbook();
  const worksheet = workbook.addWorksheet('My Sheet');

  // 示例数据
  const headers = [
    t('spectRecord.spectRecord.60zelpzsg7o0'),
    'UASID',
    t('spectRecord.spectRecord.60zelpzsji00'),
    t('spectRecord.spectRecord.60zelpzsjtk0'),
    t('spectRecord.spectRecord.60zelpzskcg0'),
    '飞行速度',
    t('spectRecord.spectRecord.60zelpzsjy13'),
    t('spectRecord.spectRecord.60zelpzskfw0'),
    t('spectRecord.spectRecord.60zelpzsjyg0'),
    // t('spectRecord.spectRecord.60zelpzsjy14'),
    t('spectRecord.spectRecord.60zelpzsj1w0')
  ];
  const list = await useLoadData(apiFiveGARecordList, {
    ...form.data,
    startTime: Number(dayjs(form.data.startTime).format('X')),
    endTime: Number(dayjs(form.data.endTime).format('X')),
  })
  let newList = list.map((item: any) => {
    return {
      ...item,
      "startTime": item.startTime,
      "endTime": item.endTime,
      "status": item.status,
      "second": item.second,
      "snId": 0,
      "businessId": item.businessId,
      "manufacturer": "string",
      "receiverMac": "string",
      "uavBasic": {
        "ID": item.objectId,
        "uavType": 0,
        "IDType": 0
      },
      "uavLocation": {
        "lat": item.latitude,
        "lon": item.longitude,
        "alit": item.altitude,
        "direc": 0,
        "status": 0,
        "speedH": item.speed,
        "speedV": 0,
        "height": item.height,
        "height_over": 0,
        "hori_acc": 0,
        "vert_acc": 0,
        "speed_acc": 0
      },
      "uavOperatorBasic": {
        "ID": 0,
        "type": 0
      },
      "uavOperatorInfo": {
        "Location Type": 0,
        "alit": 0,
        "lat": 0,
        "lon": 0,
        "area_count": 0,
        "area_rad": 0,
        "coordinate_type": 0,
        "area_ceil": 0,
        "area_floor": 0,
        "classification": 0,
        "category": 0,
        "class": 0,
        "Timestamp": "string"
      },
      "createTime": item.time,
      "rssi": 0,
      "whiteUav": {
        "id": 0,
        "uavId": "string",
        "remark": "string",
        "status": 0,
        "createTime": 0,
        "uid": "string",
        "uavNum": "string",
        "customerName": "string",
        "mobile": "string",
        "address": "string",
        "idCardNum": "string",
        "color": "string",
        "suffix": "string",
        "typeName": "string"
      }
    }
  })
  console.log(newList)
  form.downloading = false
  if (!newList.length) return useMessage.warning(t('components.cNone.60zeq5j8rrg0'))
  form.downloading = true
  // const address = useUniqueUavLocations(newList.filter((item: any) => item.uavLocation.lon !== 0 && item.uavLocation.lat))
  // const group = useChunkArray(address.map((item: any) => {
  //   return [item.uavLocation.lon, item.uavLocation.lat]
  // }))
  console.log('1')
  // const addressList = (await Promise.all(group.map((item: any) => getAddress(item))))?.flat()
  // console.log('1',addressList)
  // let enums: any = {}
  // addressList.forEach((item: any, index: any) => {
  //   let obj = address[index]
  //   enums[`${obj.uavLocation.lon},${obj.uavLocation.lat}`] = item
  // })
  // console.log(addressList)
  // console.log(enums)
  // console.log(await getAddress(address))
  const data = newList.map((item: any, index: any) => {
    return [
      index + 1,
      item.uavBasic.id || '',
      dayjs.unix(item.startTime).format('YYYY-MM-DD HH:mm:ss') || '',
      dayjs.unix(item.endTime).format('YYYY-MM-DD HH:mm:ss') || '',
      item.uavLocation.height || '',
      item.uavLocation.speedH || '',
      item.uavLocation.alit || '',
      item.second || '',
      item.uavLocation.lon + ',' + item.uavLocation.lat || '',
      // enums[`${item.uavLocation.lon},${item.uavLocation.lat}`] || '',
      item?.status == 7 ? t('spectRecord.spectRecord.60zelpzsj7o0') : t('spectRecord.spectRecord.60zelpzsjc80')
    ]
  });
  console.log(data)
  // 添加表头
  worksheet.addRow(headers);

  // 添加数据
  data.forEach((row: any) => {
    worksheet.addRow(row);
  });

  // 导出Excel
  const buffer = await workbook.xlsx.writeBuffer();
  saveAs(new Blob([buffer], { type: 'application/octet-stream' }), '5G-A无人机侦测记录.xlsx');
  form.downloading = false
}
// 查看详情
const detail = (record: any) => {
  form.detail.data = cloneDeep(record)
  form.detail.show = true
}
// 回放
const playback = (record: any) => {
  form.playback.data = cloneDeep(record)
  form.playback.show = true
}
// let geocoder: any
// // 地图初始化结束后，加载插件
// lazyAMapApiLoaderInstance.then(() => {
//   geocoder = new (window as any).AMap.Geocoder()
// })
// 使用Geocoder解析经纬度对应的地址信息
// const getAddress = (lnglat: any) => {
//   return new Promise((resolve, reject) => {
//     geocoder.getAddress(lnglat, (status: any, result: any) => {
//       if (status === 'complete' && result.info === 'OK') {
//         resolve(result?.regeocodes?.map((item: any) => item.formattedAddress))
//       } else {
//         reject(new Array(lnglat?.length).fill(''))
//       }
//     })
//   })
// }
onBeforeMount(() => {
  getData()
  local.getdroneOPeratorList()
})
onMounted(() => {
  if (route.query.objectId) {
    playback({
      objectId: route.query.objectId,
      startTime: Number(route.query.startTime),
      endTime: Number(route.query.endTime),
    })
  }
  // console.log((window as any)?.AMap?.Geocoder)
  // if ((window as any)?.AMap?.Geocoder) {
  //   geocoder = new (window as any).AMap.Geocoder()
  // }
})
</script>

<style scoped lang="less"></style>